package com.longway.common.rateLimiter;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

public class RateLimiterInterceptor implements Interceptor{
	private String cacheName;
	 
	public RateLimiterInterceptor() {
 
	}
 
	public RateLimiterInterceptor(String cacheName) {
		this.cacheName = cacheName;
	}
 
	@Override
	public void intercept(Invocation inv) {
		Controller c = inv.getController();
		RateLimiter rateLimiter = inv.getMethod().getAnnotation(RateLimiter.class);
		if (rateLimiter != null) {
			int limit = rateLimiter.limit();
			int timeout = rateLimiter.timeout();
			Cache cache = Redis.use(cacheName);
			//Jedis jedis = cache.getJedis();
			/*String token = RedisRateLimite.acquireTokenFromBucket(jedis, limit, timeout);
			if (token == null) {
				try {
					c.getResponse().sendError(500);
				} catch (IOException e) {
					e.printStackTrace();
				}
				return;
			}
			cache.close(jedis);*/
			inv.invoke();
		} else {
			inv.invoke();
		}
	}
 
}

/*@Controller
@RequestMapping(value = "/test")
public class TestController extends BaseController {
 
	@RateLimiter(limit = 1, timeout = 1000)
	public void test1() {
		renderJson(Okv.create().set("msg", "ok"));
	}
}*/
